/*
*   @Author: 1296
*   @Date: 2025-03-22
*   @Description: 账号管理
*/

<template>
  <div class="account-management">
    <!-- 头像展示部分 -->
    <div class="avatar" @click="triggerFileInput">
      <img
          :src="currentAvatar"
          alt="User Avatar"
          :class="{ 'unsaved-avatar': tempAvatar }"
          @error="setDefaultAvatar"
      />
      <input
          type="file"
          ref="fileInput"
          accept="image/jpeg, image/png"
          style="display: none"
          @change="handleFileUpload"
      />
      <p class="upload-tip">{{ $t('uploadTip') }}</p>
    </div>

    <!-- 可编辑字段 -->
    <div class="editable-fields">
      <div class="form-item">
        <label>{{ $t('role') }}</label>
        <input
            :value="roleText"
            :placeholder="$t('notProvided')"
            disabled
            class="readonly-field"
        />
      </div>
      <div v-for="(field, key) in editableFields" :key="key" class="form-item">
        <template v-if="key !== 'major' && key !== 'className'">
          <label>{{ field.label }}</label>
          <div v-if="key === 'gender'">
            <select v-model="form.gender">
              <option value="">{{ field.placeholder }}</option>
              <option value="0">{{ $t('male') }}</option>
              <option value="1">{{ $t('female') }}</option>
            </select>
          </div>
          <div v-else>
            <input v-model="form[key]" :placeholder="field.placeholder" />
          </div>
        </template>
        <template v-else-if="(key === 'major' || key === 'className') && isStudent">
          <div v-if="isStudent">
            <label>{{ field.label }}</label>
            <input v-model="form[key]" :placeholder="field.placeholder" />
          </div>
        </template>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <button class="cancel-btn" @click="cancelChanges">
        {{ $t('cancel') }}
      </button>
      <button
          class="save-btn"
          :class="{ active: isEdited }"
          @click="saveChanges"
          :disabled="!isEdited"
      >
        {{ $t('saveChanges') }}
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import defaultAvatar from '@/assets/guest.jpg'
import { mapGetters } from 'vuex'
import store from "@/store";

export default {
  name: 'AccountManagement',
  data() {
    const user = this.$store.getters
    return {
      form: {
        username: user.username || '',
        phone: user.phone || '',
        gender: user.gender || '',
        email: user.email || '',
        institute: user.institute || '',
        major: user.major || '',
        className: user.className || '',
        jobCode: user.jobCode || ''
      },
      tempAvatar: null,
      initialForm: {},
      isEdited: false,
      // 字段配置
      editableFields: {
        username: { label: this.$t('username'), placeholder: this.$t('usernamePlaceholder') },
        phone: { label: this.$t('phone'), placeholder: this.$t('phonePlaceholder') },
        gender: { label: this.$t('gender'), placeholder: this.$t('genderNotSelected') },
        email: { label: this.$t('email'), placeholder: this.$t('emailPlaceholder') },
        jobCode: { label: this.$t('jobCode'), placeholder: this.$t('jobCodePlaceholder') },
        institute: { label: this.$t('institute'), placeholder: this.$t('institutePlaceholder') },
        major: { label: this.$t('major'), placeholder: this.$t('majorPlaceholder') },
        className: { label: this.$t('className'), placeholder: this.$t('classNamePlaceholder') }
      }
    }
  },
  computed: {
    ...mapGetters(['avatar','role']),
    currentAvatar() {
      return this.tempAvatar || this.avatarSrc
    },
    roleText() {
      switch (this.role) {
        case '0':
        case 0:
          return this.$t('student')
        case '1':
        case 1:
          return this.$t('teacher')
        default:
          return this.$t('unauthorized')
      }
    },
    isStudent() {
      return this.role === '0' || this.role === 0
    },
    // 如果 avatar 存在则返回其 data URL，否则使用默认头像
    avatarSrc() {
      if (this.avatar) {
        return this.avatar.startsWith('data:image')
            ? this.avatar
            : `${this.avatar}`
      }
      return defaultAvatar
    }
  },
  created() {
    // 深拷贝初始表单数据
    this.initialForm = JSON.parse(JSON.stringify(this.form))
  },
  watch: {
    form: {
      deep: true,
      handler() {
        this.checkEditStatus()
      }
    },
    tempAvatar: {
      handler() {
        this.checkEditStatus()
      }
    }
  },
  methods: {
    // 设置默认头像
    setDefaultAvatar(event) {
      event.target.src = defaultAvatar
    },
    checkFormChanges(newForm) {
      this.isEdited = Object.keys(newForm).some(
          key => newForm[key] !== this.initialForm[key]
      )
    },
    checkEditStatus() {
      const formChanged = Object.keys(this.form).some(
          key => this.form[key] !== this.initialForm[key]
      )
      const avatarChanged = !!this.tempAvatar
      this.isEdited = formChanged || avatarChanged
    },
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleFileUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      // 验证文件类型和大小（2MB）
      const validTypes = ['image/jpeg', 'image/png']
      const maxSize = 2 * 1024 * 1024

      if (!validTypes.includes(file.type)) {
        alert(this.$t('invalidFileType'))
        return
      }

      if (file.size > maxSize) {
        alert(this.$t('fileSizeExceeded'))
        return
      }
      // 转换为Base64
      const reader = new FileReader()
      reader.onload = (e) => {
        this.tempAvatar = e.target.result
      }
      reader.readAsDataURL(file)
    },

    async saveChanges() {
      try {
        const changes = {}
        Object.keys(this.form).forEach(key => {
          if (this.form[key] !== this.initialForm[key]) {
            changes[key] = this.form[key]
          }
        })
        if (this.tempAvatar) {
          changes.avatar = this.tempAvatar
        }
        if (Object.keys(changes).length === 0) return
        const { data } = await axios.put(store.getters.getBaseURL + '/user/userInfo', changes, {
          headers: {
            Authorization: this.$store.getters.token
          }
        })
        if (data.code === 200) {
          // 更新本地存储
          const updatedUser = {
            ...this.$store.state.user,
            ...changes
          }
          this.$store.commit('SET_USER', updatedUser)

          // 重置临时数据
          this.tempAvatar = null
          this.initialForm = JSON.parse(JSON.stringify(this.form))
          this.isEdited = false
          alert(this.$t('saveSuccess'))
        }
      } catch (error) {
        console.error('保存失败:', error)
        alert(`${this.$t('saveFail')}: ${error.response?.data?.info || this.$t('networkError')}`)
      }
    },
    cancelChanges() {
      // 恢复原始数据
      this.form = JSON.parse(JSON.stringify(this.initialForm))
      this.tempAvatar = null
      this.isEdited = false
    },
  }
}
</script>

<style scoped>
.account-management {
  max-width: calc(640 / 1920 * 100vw);
  margin: 0 auto;
  padding: 2rem;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.avatar {
  text-align: center;
  margin-bottom: 2.5rem;
}

.upload-tip {
  margin-top: 0.5rem;
  font-size: 0.8rem;
  color: #718096;
  text-align: center;
}

.unsaved-avatar {
  border-color: #48bb78 !important;
  animation: pulse-border 1.5s infinite;
}

@keyframes pulse-border {
  0% { box-shadow: 0 0 0 0 rgba(72,187,120,0.2); }
  70% { box-shadow: 0 0 0 8px rgba(72,187,120,0); }
  100% { box-shadow: 0 0 0 0 rgba(72,187,120,0); }
}

.avatar img {
  width: calc(128 / 1920 * 100vw);
  height: calc(128 / 1920 * 100vw);
  border-radius: 50%;
  object-fit: cover;
  border: 8px solid #d6d6d6;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.avatar img:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.editable-fields {
  display: grid;
  gap: 1.5rem;
}

.form-item {
  display: grid;
  gap: 0.5rem;
}

.form-item label {
  font-weight: 500;
  color: #2d3748;
  font-size: 0.95rem;
}

.form-item input,
.form-item select {
  width: 90%;
  padding: 0.75rem 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.95rem;
  transition: border-color 0.2s ease;
}

.form-item input:focus,
.form-item select:focus {
  outline: none;
  border-color: #48bb78;
  box-shadow: 0 0 0 3px rgba(72, 187, 120, 0.1);
}

.form-item select {
  appearance: none;
  background: url("@/assets/select-arrow.svg") no-repeat right 1rem center/16px 24px;
}

.action-buttons {
  margin-top: 2rem;
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

button {
  padding: 0.75rem 1.75rem;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}

.cancel-btn {
  background-color: #f8f9fa;
  color: #4a5568;
}

.cancel-btn:hover {
  background-color: #e2e8f0;
  transform: translateY(-1px);
}

.save-btn {
  background-color: #e2e8f0;
  color: #718096;
}

.save-btn.active {
  background-color: #48bb78;
  color: white;
}

.save-btn.active:hover {
  background-color: #38a169;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(72, 187, 120, 0.2);
}

.save-btn:disabled {
  cursor: not-allowed;
  opacity: 0.7;
  transform: none;
}

.readonly-field {
  background-color: #f8f9fa;
  cursor: not-allowed;
  border-color: #e2e8f0 !important;
  color: #718096;
}

@media (max-width: calc(640 / 1920 * 100vw)) {
  .account-management {
    padding: 1.5rem;
    margin: 0 1rem;
  }

  .avatar img {
    width: calc(96 / 1920 * 100vw);
    height: calc(96 / 1920 * 100vw);
  }

  button {
    padding: 0.6rem 1.25rem;
    font-size: 0.9rem;
  }
}
</style>
